import {mExportUserList, mSelectUserListByPage} from '@/api/user'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {downFile} from '@/libs/toolkit'
import {PropType} from 'vue'
import {CoustomTableFn} from '@/components/table'
import CoustomForm from '@/components/form'
import {time2str} from '@/libs/date'
/**设备列表 状态数据 */
let user_list_state = reactive<{
  /**弹窗 */
  modal: {
    /**弹窗 关闭*/
    visible: boolean
    /**弹窗 类型*/
    type: string
    /**弹窗 标题*/
    title: string
  }
  table: CTable<User.LoginUserInfo>
  search: {
    userName: string
    userPhone: string
  }
}>({
  modal: {
    visible: false,
    type: '',
    title: '',
  },
  table: {
    dataSource: [],
    pagination: {
      page: 1,
      size: 20,
    },
    total: 0,
    loading: false,
    onPaginatiChange({page, size}) {
      let {pagination} = toRefs(user_list_state.table)
      pagination.value.page = page
      pagination.value.size = size
      getTableDatas()
    },
  },
  search: {
    userName: '',
    userPhone: '',
  },
})

/**获取表格数据 */
export async function getTableDatas() {
  let {
    dataSource,
    pagination,
    loading,
    total: tableTotal,
  } = toRefs(user_list_state.table)
  let {search} = toRefs(user_list_state)
  loading.value = true
  let defaultData = {
    page: 1,
    size: 20,
    start: 0,
    userPhone: '',
    userName: '',
  }
  Object.assign(defaultData, pagination.value, search.value)
  let res = await mSelectUserListByPage(defaultData).catch(err => {})
  if (res) {
    let {list, total} = res.data
    dataSource.value = list
    tableTotal.value = total
  }
  loading.value = false
}

/**设备列表 左侧搜索 筛选区域 */
export const ViewLeftFilter = defineComponent({
  name: 'ViewLeftFilter',
  setup(props, {emit}) {
    let {search} = toRefs(user_list_state)
    return () => (
      <CoustomForm
        class="h-full"
        model={search.value}
        labelCol={{span: 0}}
        wrapperCol={{span: 24}}
        footerClass="absolute left-0 bottom-0 m-0 px-4 border-t border-default flex justify-end items-center"
        onFormSubmit={formRef => {
          getTableDatas()
        }}
        onFormReset={() => {
          getTableDatas()
        }}
      >
        <a-form-item name="userName" class="mx-2 my-4">
          <a-input
            v-model={[search.value.userName, 'value']}
            placeholder="用户名称"
            allowClear
          >
            {{
              prefix: () => <i class="iconfont icon-touxiang text-primary"></i>,
            }}
          </a-input>
        </a-form-item>
        <a-form-item name="userPhone" class="mx-2 my-4">
          <a-input
            v-model={[search.value.userPhone, 'value']}
            placeholder="用户手机号"
            allowClear
          >
            {{
              prefix: () => (
                <i class="iconfont icon-shoujihao text-primary"></i>
              ),
            }}
          </a-input>
        </a-form-item>
      </CoustomForm>
    )
  },
})

/**设备列表 表格上方操作栏 */
export const TypeMainViewNav = defineComponent({
  setup() {
    let {router} = useGlobalAPI()
    // let {visible, type, title} = toRefs(user_list_state.modal)

    const handle_export_btn_click = async () => {
      let res = await mExportUserList()
      if (!res) return
      // res.arrayBuffer().then(data => {
      //   mammoth.convertToHtml({arrayBuffer: data}).then(data1 => {
      //     console.log(data1)
      //   })
      // })
      downFile(res.data, '用户列表')
    }
    return () => (
      <div class="w-full h-mainViewNav border-b border-default bg-white px-4 flex justify-end items-center">
        <a-button type="primary" onClick={handle_export_btn_click}>
          导出列表
        </a-button>
      </div>
    )
  },
})

/**用户列表 表格 操作栏 */
const HandleBtn = defineComponent({
  props: {
    record: {
      type: Object as PropType<User.LoginUserInfo>,
      default: {},
    },
  },
  setup(props) {
    let {record} = toRefs(props)

    const handle_checkDevice_by_userId = async () => {
      let {router} = useGlobalAPI()
      router.push({
        name: 'device-list',
        params: {
          userId: record.value.userId,
          userPhone: record.value.userPhone,
          userCompany: record.value.userCompany,
        },
      })
    }
    return () => (
      <div>
        {/* <span
          class=" mr-2 text-primary border-b cursor-pointer"
          onClick={handle_checkDevice_by_userId}
        >
          查看设备
        </span> */}
      </div>
    )
  },
})

/**用户列表 表格 */
const CoustomTable = CoustomTableFn<User.LoginUserInfo>()
export const MainViewContent = defineComponent({
  name: 'MainViewContent',
  setup(props) {
    let {dataSource, loading, total, onPaginatiChange} = toRefs(
      user_list_state.table
    )
    let {page, size} = toRefs(user_list_state.table.pagination)

    /**表格头 */
    let columns: CColumn<User.LoginUserInfo>[] = [
      {
        title: '公司名称',
        dataIndex: 'userCompany',
        ellipsis: true,
        customRender(data) {
          return (
            <div class="truncate">
              <a-tooltip title={data.text}>{data.text}</a-tooltip>
            </div>
          )
        },
      },
      {
        title: '用户名称',
        dataIndex: 'userName',
        ellipsis: true,
        customRender(data) {
          return (
            <div class="truncate">
              <a-tooltip title={data.text}>{data.text}</a-tooltip>
            </div>
          )
        },
      },
      {
        title: '用户昵称',
        dataIndex: 'userNearName',
        ellipsis: true,
        customRender(data) {
          return (
            <div class="truncate">
              <a-tooltip title={data.text}>{data.text}</a-tooltip>
            </div>
          )
        },
      },
      {
        title: '手机号',
        dataIndex: 'userPhone',
        ellipsis: true,
        width: 180,
        customRender(data) {
          return (
            <div class="truncate">
              <a-tooltip title={data.text}>{data.text}</a-tooltip>
            </div>
          )
        },
      },
      {
        title: '邮箱',
        dataIndex: 'userEmail',
        ellipsis: true,
        width: 180,
        customRender(data) {
          return (
            <div class="truncate">
              <a-tooltip title={data.text}>{data.text}</a-tooltip>
            </div>
          )
        },
      },
      {
        title: '创建时间',
        dataIndex: 'userCreateTime',
        ellipsis: true,
        width: 120,

        customRender(data) {
          return (
            <div class="truncate">
              <a-tooltip title={data.text || '无创建时间'}>
                {time2str(data.text)}
              </a-tooltip>
            </div>
          )
        },
      },
      {
        title: '最近登录',
        dataIndex: 'userLastLogin',
        ellipsis: true,
        width: 120,

        customRender(data) {
          return (
            <div class="truncate">
              <a-tooltip title={data.text || '无登录时间'}>
                {time2str(data.text)}
              </a-tooltip>
            </div>
          )
        },
      },
      {
        title: '是否绑定微信',
        dataIndex: 'userWeichatId',
        ellipsis: true,
        width: 120,
        customRender(data) {
          if (
            data.record.userWeichatId !== null &&
            data.record.userWeichatId !== undefined
          ) {
            return <div class="truncate text-success">已绑定</div>
          } else {
            return <div class="truncate text-danger"> 未绑定</div>
          }
        },
      },
      {
        title: '操作',
        dataIndex: 'utils',
        isUtil: true,
        width: 140,
        customRender(data) {
          return <HandleBtn record={data.record}></HandleBtn>
        },
      },
    ]

    return () => (
      <CoustomTable
        dataSource={dataSource.value}
        loading={loading.value}
        rowKey="userId"
        columns={columns}
        pagination={{
          page: page.value,
          size: size.value,
          total: total.value,
        }}
        onPaginationChange={data => onPaginatiChange.value(data)}
        isDefaultBodyCell={false}
      >
        {/* {{
          util: (record: User.LoginUserInfo) => (
            <HandleBtn record={record}></HandleBtn>
          ),
        }} */}
      </CoustomTable>
    )
  },
})

/**设备列表 弹窗 */
export const TypeModel = defineComponent({
  setup(props, {emit}) {
    let {visible, type, title} = toRefs(user_list_state.modal)
    const handle_form_finish = () => {
      visible.value = false
      type.value = ''
      getTableDatas()
    }
    return () => {
      let dynamicCom = <div></div>
      // switch (type.value) {
      //     case 'addType':
      //         dynamicCom = (
      //             <AddDeviceTypeDatasForm
      //                 onFinish={handle_form_finish}
      //             ></AddDeviceTypeDatasForm>
      //         )
      //         break
      // }
      return (
        <a-modal
          visible={visible.value}
          title={title.value}
          footer={null}
          onCancel={() => {
            handle_form_finish()
          }}
        >
          {dynamicCom}
        </a-modal>
      )
    }
  },
})
